<?php
/**
 * User: PunkVv <punkvv@qq.com>
 * Date: 2016/7/8
 * Time: 18:06
 */
namespace app\common\controller;

use think\Exception;
use think\Request;
use think\View;


/**
 * 插件类
 * Class Addon
 * @package app\common\controller
 */
abstract class Addon
{
    protected $view = null;
    public $info = array();
    public $addonPath = '';
    public $configFile = '';
    public $customConfig = '';
    public $adminList = array();
    public $customAdminList = '';
    public $accessUrl = array();

    /**
     * 构造方法
     */
    public function __construct()
    {
        $this->view = new View();
        $this->addonPath = substr(ROOT_PATH, 0, strlen(ROOT_PATH) - 11) . '/addons/' . $this->getName();
        if (is_file($this->addonPath . '/config.php')) {
            $this->configFile = $this->addonPath . '/config.php';
        }
    }

    /**
     * 显示方法
     * @param string $template
     */
    final protected function display($template = '')
    {
        if ($template == '') {
            $template = Request::instance()->controller();
        }
        echo($this->fetch($template));
    }


    /**
     * 显示方法
     * @param string $templateFile
     * @return string
     * @throws Exception
     */
    final protected function fetch($templateFile = '')
    {
        if ($templateFile == '') {
            $templateFile = Request::instance()->controller();
        }
        if (!is_file($templateFile)) {
            $templateFile = $this->addonPath . '/' . $templateFile . '.' . config('template')['view_suffix'];
            if (!is_file($templateFile)) {
                throw new Exception("模版不存在：$templateFile");
            }
        }
        return $this->view->fetch($templateFile);
    }

    /**
     * 模版变量赋值
     * @param $name
     * @param string $value
     * @return $this
     */
    final protected function assign($name, $value = '')
    {
        $this->view->assign($name, $value);
        return $this;
    }

    /**
     * 获取名称
     */
    final public function getName()
    {
        $class = get_class($this);
        return substr($class, strrpos($class, '\\') + 1, -5);
    }
}